package com.yanh.jcommon.interceptor;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.yanh.jcommon.constant.AuthServerConstant;
import com.yanh.jcommon.constant.CartConstant;
import com.yanh.jcommon.utils.UserContext;
import com.yanh.jcommon.vo.member.MemberResponseVo;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;

/**
 * @author
 * @createDate
 * @description 自定义拦截器(设置用户信息)
 */


@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserContext> toThreadLocal = new ThreadLocal<>();

    /**
     * 业务执行之前
     * 拦截所有请求给每个线程封装UserInfoTo对象
     * 1、从session中获取MemberResponseVo != null(登录状态)，为UserInfoTo设置userId
     * 2、从request中获取cookie，找到user-key的value，为UserInfoTo设置userKey和tempUser
     * 目标方法执行之前：在ThreadLocal中存入用户信息【同一个线程共享数据】
     * 从session中获取数据【使用session需要cookie中的GULISESSION 值】
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserContext userInfoTo = new UserContext();
        HttpSession session = request.getSession();
        MemberResponseVo memberRespVo = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(memberRespVo!=null){
            // 用户登录
            userInfoTo.setUserId(memberRespVo.getId());
        }

        Cookie[] cookies = request.getCookies();
        if(ArrayUtil.isNotEmpty(cookies)){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }

        // 如果没有临时用户，分配一个临时用户
        if(StrUtil.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

//        // 测试用户
//        userInfoTo.setUserId(1L);

        toThreadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后:分配临时用户，让浏览器保存
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 设置Cookie ：user-key标识用户身份，一个月过期
        UserContext userInfoTo = toThreadLocal.get();
        // 如果没有临时用户保存一个临时用户
        if(!userInfoTo.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("jmall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}